<?php

namespace app\admin\model\xmwms;

use think\Model;

class RelocationDetail extends Model
{
    // 表名
    protected $name = 'wms_relocation_detail';

    protected $warehouseModel;

    /**
     * @var string 自动写入时间戳字段
     */
    protected $autoWriteTimestamp = true;

    protected $append = [
        'source_warehouse_shelf_id_text',
        'target_warehouse_shelf_id_text',
    ];

    // 字段类型转换
    protected $type = [
        'deletetime' => 'timestamp:Y-m-d H:i:s',
    ];


    public function getSourceWarehouseShelfIdTextAttr($value, $row): string
    {
        $this->warehouseModel = new Warehouse();
        if (isset($row['warehouse_shelf_id']) && $row['warehouse_shelf_id'] > 0) {
            $data = $this->warehouseModel->where('id', $row['warehouse_shelf_id'])->find();
            if ($data['warehouse_type'] == 'warehouse_shelf') {
                $warehouse_area = $this->warehouseModel->where('id', $data['pid'])->find();
                $warehouse      = $this->warehouseModel->where('id', $warehouse_area['pid'])->value('name');
                return $warehouse . '/' . $warehouse_area['name'] . '/' . $data['name'];
            } elseif ($data['warehouse_type'] == 'warehouse_area') {
                $warehouse = $this->warehouseModel->where('id', $data['pid'])->value('name');
                return $warehouse . '/' . $data['name'];
            } else {
                return $data['name'];
            }
        } else {
            return '';
        }
    }

    public function getTargetWarehouseShelfIdTextAttr($value, $row): string
    {
        if (isset($row['warehouse_shelf_id']) && $row['warehouse_shelf_id'] > 0) {
            $data = $this->warehouseModel->where('id', $row['warehouse_shelf_id'])->find();
            if ($data['warehouse_type'] == 'warehouse_shelf') {
                $warehouse_area = $this->warehouseModel->where('id', $data['pid'])->find();
                $warehouse      = $this->warehouseModel->where('id', $warehouse_area['pid'])->value('name');
                return $warehouse . '/' . $warehouse_area['name'] . '/' . $data['name'];
            } elseif ($data['warehouse_type'] == 'warehouse_area') {
                $warehouse = $this->warehouseModel->where('id', $data['pid'])->value('name');
                return $warehouse . '/' . $data['name'];
            } else {
                return $data['name'];
            }
        } else {
            return '';
        }
    }

    public function relocation()
    {
        return $this->belongsTo(Relocation::class, 'relocation_no', 'relocation_no');
    }

    public function product()
    {
        return $this->belongsTo(Product::class, 'product_id', 'id');
    }

}